import os
import shutil
from com.garmin.utils import adb, gos

def copyCrashReport(src, dest):
    if not os.path.exists(src):
        return False
    if os.path.isfile(src):
        if not os.path.exists(dest):
            os.mkdir(dest)
        shutil.copy(src,  os.path.join(dest, "CrashReport.txt"))
    elif os.path.isdir(src):
        if os.path.exists(dest):
            os.rmdir(dest)
    #Check is the crash report exist
        if not os.path.exists(os.path.join(src, "CrashReport.txt")):
            print "No CrashReport.txt found in the source folder"
            return False
        shutil.copytree(src, dest)
    return True
def pullCrashReport(dest):
    if not os.path.exists(dest):
        os.makedirs(dest)
    adb.pullTo("/sdcard/Garmin/Diag/", dest)
    print "pull crash report success!"
    return True
def pullANRReport(dest):
    if not os.path.exists(dest):
        os.makedirs(dest)
    adb.pullTo("/data/anr/", dest)
    print "pull anr report success!"
    return True
def _tar(execPath, source, target, filename=""):
    if os.path.exists(target):
        os.remove(target)
    command = execPath + " zcvf " + target + " " + source
    output = gos.execute(command);
    return output
def _sevenZ(execPath, source, target, filename=""):
    if os.path.exists(target):
        os.remove(target)
    command = execPath + " a -tzip " + target + " " + source
    output = gos.execute(command);
    return output
def _buildCompressToolPath():
    osName = gos.getOSName()
    compressTool = {'7z':None, 'zip' : None, 'tar' : None}
    # If os is windows
    if osName.find("Win") != -1 or osName.find("MINGW") != -1:
        tempPath = "C:\\Program Files\\7-Zip\\7z.exe"
        if not os.path.isfile(tempPath):
            tempPath = "C:\\Program Files (x86)\\7-Zip\\7z.exe"
            if not os.path.isfile(tempPath):
                tempPath = ""
        compressTool['7z'] = {'command' : _sevenZ, 'execPath' : tempPath}
    elif osName.find("Linux") != -1:
        compressTool['tar'] = {'command' : _tar, 'execPath' : 'tar'}
    return compressTool
def compressDir(src, dest):
    compressTool = _buildCompressToolPath()
    output = None

    current_path = os.getcwd();
    os.chdir(src)
    for key, value in compressTool.iteritems():
        if value is not None:
            output = value['command'](value['execPath'], "./", os.path.join(current_path, dest))
            break
    
    os.chdir(current_path)
    if output is not None:
        if output['stdout'] is not "":
            return True
    return False